#pragma once
// epoll的增删改操作

#pragma once
#include <iostream>
#include <string>
#include <vector>
#include <sys/epoll.h>
#include <errno.h>
#include "Logger.hpp"
#include <unistd.h>
#include <vector>

class Epoller
{
    static const int epoll_default_size = 64; // 本身是框定epoll红黑树大小的数字，但是现在已被忽略
    static const int default_epoll_queue = 64;
public:
    Epoller():_queue(default_epoll_queue)
    {
        _epfd = epoll_create(epoll_default_size);
        if (_epfd < 0)
        {
            LOG(LogLevel::ERROR) << "epoll_create error";
            exit(errno);
        }
        LOG(LogLevel::INFO) << "epoll_create success";
    }

    void Add(int fd, uint32_t event)
    {
        struct epoll_event sock;
        sock.events = event;
        sock.data.fd = fd;
        if (epoll_ctl(_epfd, EPOLL_CTL_ADD, fd, &sock) != 0)
        {
            LOG(LogLevel::ERROR) << "epoll_add error";
            exit(errno);
        }
    }

    void Mod(int fd, uint32_t event)
    {
        struct epoll_event sock;
        sock.events = event;
        sock.data.fd = fd;
        if (epoll_ctl(_epfd, EPOLL_CTL_MOD, fd, &sock) != 0)
        {
            LOG(LogLevel::ERROR) << "epoll_mod error";
            exit(errno);
        }
    }

    void Del(int fd)
    {
        if (epoll_ctl(_epfd, EPOLL_CTL_DEL, fd, nullptr) != 0)
        {
            LOG(LogLevel::ERROR) << "epoll_del error";
            exit(errno);
        }
    }

    int Wait()
    {
        int n = epoll_wait(_epfd,&_queue[0],_queue.size(),-1);//设置成阻塞模式
        if(n < 0)
        {
            LOG(LogLevel::ERROR) << "epoll_wait error";
            exit(errno);
        }
        return n;
    }

    std::vector<struct epoll_event>& GetQueue()
    {
        return _queue;
    }

    ~Epoller()
    {
    }

private:
    int _epfd; // 管理整个epoll
    std::vector<struct epoll_event> _queue;//就绪队列
};
